package com.iwhalecloud.bss.kite.cucc.service.order;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import org.springframework.stereotype.Service;

import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.common.util.TransactionUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.job.collectiongroup.ICollectionGroupTask;
import com.iwhalecloud.bss.kite.cucc.client.dto.batch.KiteBatchAcceptDetail;
import com.iwhalecloud.bss.kite.cucc.client.dto.batch.KiteBatchAcceptDetailDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.dataservice.mapper.batch.KiteBatchAcceptDetailMapper;
import com.iwhalecloud.bss.kite.cucc.dataservice.mapper.batch.KiteBatchAcceptMapper;
import com.iwhalecloud.bss.kite.cucc.service.batch.BatchAcceptUtil;
import com.iwhalecloud.bss.kite.cucc.service.job.collectiongroup.StatusConst;
import com.iwhalecloud.bss.kite.cucc.service.job.collectiongroup.singletask.AbstractSingleTask;
import com.iwhalecloud.bss.kite.cucc.service.job.collectiongroup.singletask.AddGroupSingleTask;
import com.iwhalecloud.bss.kite.dataservice.cache.DcSystemParamCache;
import com.ztesoft.common.logger.api.ZLogger;
import com.ztesoft.common.logger.factory.ZLoggerFactory;

/**
 * 1、获取明细表未校验的数据,执行校验规则,更新明细表数据状态,校验成功的数据则进行转单处理,校验失败则记录失败原因。
 * 本方法采取对每一个成员先校验再进行转单,一定程度上可以避免批量校验或转单对下游系统的压力。
 * Created by huanghaosheng on 2021/3/1 16:45
 */
@Service
public class CollectionGroupTask implements ICollectionGroupTask {

    @Resource
    private KiteBatchAcceptMapper kiteBatchAcceptMapper;

    @Resource
    private KiteBatchAcceptDetailMapper kiteBatchAcceptDetailMapper;

    @Override
    public void checkStatusAndTransferOrder() {
        String batchNum = DcSystemParamCache.getDcParamVal("collect_revenue_batch_num");
        Integer dealNum = Integer.parseInt(KiteStringUtils.isNotEmpty(batchNum) ? batchNum : "50");

        List<Map<String, Object>> batchList = this.kiteBatchAcceptMapper.listTodoBatch(LocalKeyConsts.COLLECTION_GROUP_IMPORT_TYPE_1000);
        if (KiteListUtils.isEmpty(batchList)) {
            return;
        }
        batchList.forEach(batch -> {
            String batchId = KiteMapUtils.getString(batch, "batch_id");
            // 待处理的任务
            List<KiteBatchAcceptDetailDTO> kiteBatchAcceptDetails = kiteBatchAcceptDetailMapper
                .listKiteBatchAcceptDetailByBatchId(batchId, LocalKeyConsts.COLLECTION_GROUP_IMPORT_TYPE_1000, StatusConst.NOT_STATUSCD,
                    dealNum);
            if (KiteListUtils.isEmpty(kiteBatchAcceptDetails)) {
                // 明细处理完成后，更新批次状态
                this.updateBatchStatus(batchId, StatusConst.BATCH_STATUS_FINISH, "批量处理成功");
                return;
            }
            try {
                // 批量以批次号分库，跨批次数据不能在同一个事务中更新
                Map<Long, List<KiteBatchAcceptDetailDTO>> batchMap = kiteBatchAcceptDetails.stream().collect(Collectors.groupingBy(KiteBatchAcceptDetail::getBatchId));
                batchMap.forEach((key, list) -> {
                    TransactionUtils.executeNew(() -> {
                        List<KiteBatchAcceptDetail> _list = KiteBeanUtils.copyPropsForList(list, KiteBatchAcceptDetail.class);
                        kiteBatchAcceptDetailMapper.updateRandomNumByDetail(BatchAcceptUtil.createRandom(), _list, _list.size());
                    });
                });

                for (KiteBatchAcceptDetailDTO kiteBatchAcceptDetail : kiteBatchAcceptDetails) {
                    AbstractSingleTask addGroupSingleTask = new AddGroupSingleTask(kiteBatchAcceptDetail);
                    addGroupSingleTask.run();
                }

                // 明细处理完成后，更新批次状态
                this.updateBatchStatus(batchId, StatusConst.BATCH_STATUS_FINISH, "批量处理成功");
            }
            catch (Exception e) {
                // 明细处理完成后，更新批次状态
                this.updateBatchStatus(batchId, StatusConst.BATCH_STATUS_FINISH, "批次处理失败：" + e.getMessage());
            }
        });
    }

    private void updateBatchStatus(String batchId, String statusCd, String statusDesc) {
        // 待处理的任务
        List<KiteBatchAcceptDetail> kiteBatchAcceptDetails = kiteBatchAcceptDetailMapper
            .listNotDealDetail(batchId, LocalKeyConsts.COLLECTION_GROUP_IMPORT_TYPE_2000);
        // 未处理明细为空，则更新批次状态为1500
        if (KiteListUtils.isEmpty(kiteBatchAcceptDetails)) {
            TransactionUtils.executeNew(() -> kiteBatchAcceptMapper.updateKiteBatchAcceptStatus(statusCd, statusDesc, Long.parseLong(batchId)));
        }
    }
}
